package com.scalar.chiptrack.adaptor.wipfed;

import com.scalar.chiptrack.jobs.JobHandler;
import com.scalar.chiptrack.adaptor.AdaptorConstants;
import com.scalar.chiptrack.adaptor.AdaptorUtils;
import com.scalar.chiptrack.adaptor.dao.AdaptorRunInfo;
import com.scalar.chiptrack.utils.Logger;
import com.scalar.chiptrack.utils.ConfigManager;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.ScalarException;
import com.enterprisedt.net.ftp.FTPClient;
import com.enterprisedt.net.ftp.FTPTransferType;
import com.enterprisedt.net.ftp.FTPConnectMode;
import com.enterprisedt.net.ftp.FTPException;

import java.io.FileOutputStream;
import java.io.IOException;

/**
 * User: ChandraSekhar
 * Date: Jun 20, 2007
 * Time: 12:53:54 PM
 */
public class WipFedSortAdaptor extends JobHandler implements AdaptorConstants
{
    private static final String HOST                    = "sl.scalarsoft.com";
    private static final int SOURCE_WIP_PORT            = 21;
    public static final String FILE_NAME_WAFER_INVTY    = "wafer_invty";
    public static final String ADAPTOR_NAME             = "WIPFED_SORT";

    private String m_dataOutputDir  = null;
    private String m_username       = "spectra";
    private String m_password       = "SpArv03!";
    private Logger m_adaptorLogger  = null;
    private int    m_adaptor_id     = -1;
    
    public WipFedSortAdaptor() throws Exception
    {
       try
        {
            m_dataOutputDir = ConfigManager.getWipFedSortSheetDirectory();
            if ( m_dataOutputDir != null )
            {
                AdaptorUtils.makeAllAdaptorDirs( m_dataOutputDir );
                m_adaptorLogger = AdaptorUtils.getAdaptorLogger( m_dataOutputDir, "WIPFED SORT");
                AdaptorUtils.setLogger( m_adaptorLogger);
            }
        }
        catch (Exception se)
        {
            log("ERROR!! ERROR!! ERROR!! Exception while loading WipFed Sort out put directory details from database, Exception: " + se);
            throw se;
        }
    }


    public static void main(String[] args) throws Exception
    {
        new WipFedSortAdaptor().execute();
    }


    public void execute() throws Exception
    {
        try
        {
            m_adaptor_id = AdaptorRunInfo.saveAdaptorLastUpdatedStatus( CONSTANT_ADAPTOR, ADAPTOR_NAME, CONSTANT_SUCCESS, -1);

            /* prints the version Info*/
            AdaptorUtils.printHeader("WIPFED SORT", CONSTANT_ADAPTOR );
            /**
             * Remove the files which are already existing in local directory to remove folder
             */
            AdaptorUtils.removeOldFiles(m_dataOutputDir, m_adaptorLogger);
            /**
             * Login to SPECTRA Sort FTP Site
             */
            FTPClient ftp = login(HOST, SOURCE_WIP_PORT, m_username, m_password);

            if (ftp != null)
            {
                /**
                 * Log the info into the Log directory
                 */
                log("Successfully logged in to " + HOST);
                System.out.println("Successfully logged in to " + HOST);

                ftp.chdir("/");

                //downloading Wip file
                downloadWipFile(ftp);

                /**
                 * logout from the site
                 */
                logout(ftp);
                log("\nSuccessfully logged out from SPECTRA Sort FTP site");
                System.out.println("\nSuccessfully logged out from SPECTRA Sort FTP site");
            }
            else
            {
                log("Unable to login to the SPECTRA Sort FTP site");
                throw new ScalarException("Unable to login to the SPECTRA Sort FTP site");
            }
        }
        catch (Exception e)
        {
            AdaptorUtils.removeOldFiles(m_dataOutputDir, m_adaptorLogger);
            AdaptorRunInfo.updatedAdaptorStatus( CONSTANT_FAILURE, m_adaptor_id);
            System.out.println("Exception while trying to connect and read data from " + HOST +" site: " + e);
            log("Exception while trying to connect and read data from " + HOST +" site: " + e);
            e.printStackTrace();
            throw e;
        }
    }

    /**
     *
     * @param host
     * @param port
     * @param m_username
     * @param m_password
     * @return
     * @throws Exception
     */
    private FTPClient login(String host, int port, String m_username, String m_password) throws Exception
    {
        FTPClient ftp = null;

        try
        {
            ftp = new FTPClient(host, port);
            ftp.login(m_username, m_password);
            ftp.debugResponses(false);
            ftp.setType(FTPTransferType.BINARY);
            ftp.setConnectMode(FTPConnectMode.PASV );
        }
        catch (Exception e)
        {
            log("Could Not able to connect to the SPECTRA Sort FTP site, Exception : " + e);
            throw new ScalarException("Could Not able to connect to the SPECTRA Sort FTP site");
        }

        return ftp;
    }
    /**
     *
     * @param ftp
     * @throws Exception
     */
    private void downloadWipFile(FTPClient ftp) throws Exception
    {
        String[] fileListings = ftp.dir();

        if ((fileListings == null) || (fileListings.length == 0))
        {
            return;
        }

        byte[] buf = null;

        FileOutputStream fileOutputStream = null;
        try
        {
            String tempFileName = null;
            try
            {
                log("\nProcessing the files to downlaod.....");
                System.out.println("\nProcessing the files to downlaod.....");
                for (int k = 0; k < fileListings.length; k++)
                {
                    if (fileListings[k].startsWith( FILE_NAME_WAFER_INVTY ) )
                    {
                        if ( tempFileName == null )
                        {
                            tempFileName = fileListings[k];
                        }
                        else
                        {
                            String tempfileDateAsString = tempFileName.substring( tempFileName.lastIndexOf("wafer_invty_") + 12, tempFileName.lastIndexOf("wafer_invty_") + 18 ) ;
                            String fileDateAsString = fileListings[k].substring( fileListings[k].lastIndexOf("wafer_invty_") + 12, fileListings[k].lastIndexOf("wafer_invty_") + 18 );

                            tempfileDateAsString = StringUtils.formatDate( tempfileDateAsString, "MMddyy", "yyyy-MM-dd HH:mm:ss" );
                            fileDateAsString = StringUtils.formatDate( fileDateAsString, "MMddyy", "yyyy-MM-dd HH:mm:ss" );

                            java.util.Date tempfileDate = StringUtils.format( tempfileDateAsString, "yyyy-MM-dd HH:mm:ss");
                            java.util.Date fileDate = StringUtils.format( fileDateAsString, "yyyy-MM-dd HH:mm:ss");

                            if ( fileDate != null && tempfileDate != null )
                            {
                                if ( fileDate.compareTo( tempfileDate ) >= 0 )
                                {
                                    tempFileName = fileListings[k];
                                }
                            }
                        }
                    }
                }
                if (tempFileName != null)
                {
                    log("\ndownloading file " + tempFileName + " to " + m_dataOutputDir + " directory... ");
                    System.out.println("\n\tdownloading file " + tempFileName + " to " + m_dataOutputDir + " directory... ");
                    if ( m_adaptor_id > 0 )
                    {
                        AdaptorRunInfo.saveAdaptorFileInfo( m_adaptor_id , tempFileName.substring(0, tempFileName.indexOf(".") ), FILE_EXTN_CSV, StringUtils.formatDateToString(ftp.modtime(tempFileName), "MM/dd/yyyy HH:mm:ss" ) ) ;
                    }

                    buf = ftp.get( tempFileName );

                    tempFileName = tempFileName.substring( 0, tempFileName.indexOf('.') )  + "_" +AdaptorUtils.getTimeAsString() +"." + AdaptorUtils.FILE_EXTN_CSV;
                    fileOutputStream = new FileOutputStream( m_dataOutputDir + "/" + tempFileName, false);
                    fileOutputStream.write( buf );
                    fileOutputStream.flush();
                    fileOutputStream.close();
                    fileOutputStream = null;
                    log("\nDone... ");
                    System.out.println("Done... ");
                }
            }
            catch (FTPException fte)
            {
                throw fte;
            }
        }
        catch (IOException e)
        {
            throw e;
        }

        finally
        {
            if (fileOutputStream != null)
            {
                try
                {
                    fileOutputStream.close();
                    fileOutputStream = null;
                }
                catch (IOException ignore) {
                }
            }
        }
    }

    /**
     *
     * @param ftp
     * @throws Exception
     */
    private void logout(FTPClient ftp) throws Exception
    {
        if (ftp == null)
        {
            return;
        }

        try
        {
            ftp.quit();
        }
        catch (Exception ignore)
        {
            System.out.println("Exception Occuered While Logging Out From WipFed FTP Site" + ignore);
            throw new ScalarException("Exception Occuered While Logging Out From WipFed FTP Site" + ignore);
        }
        ftp = null;
    }

    private void log(String message)
    {
        if (message == null) return;

        if ( m_adaptorLogger != null)
        {
            synchronized (m_adaptorLogger)
            {
                m_adaptorLogger.logDebug(message + LINE_SEPARATOR);
            }
        }
        else
        {
            System.out.println(message);
        }
    }
}

